/**
 * 主线程 工具方法封装
 */

import * as fs from 'fs';
import * as path from 'path';
import axios from 'axios';

/**
 * 给渲染进程发送信息 (通知窗口大小更新了,并给予值)
 */
export function sendUpdateWinSize(mainWindow) {
    // 获取窗口大小
    let winSize = mainWindow.getSize();
    // 给渲染进程发送信息
    mainWindow.webContents.send('update-win-size', winSize);
}

/**
 * 下载文件
 * @param {string} url 要下载的文件的 URL
 * @param {string} savePath：文件保存的路径
 * @param {string} fileName 保存的文件名
 * @param {Function} progressCallback 用于接收下载进度的回调函数，它会在进度更新时被调用，参数为下载百分比（0-100）
 * @returns 
 */
export function downloadFile(url, savePath, fileName, progressCallback) {
  if(!fs.existsSync(savePath)){
    fs.mkdirSync(savePath, { recursive: true });//创建目录
  }
    const filePath = path.join(savePath, fileName);
  
    return new Promise((resolve, reject) => {
      axios({
        url: url,
        method: 'GET',
        responseType: 'stream',
      })
        .then(response => {
          const writer = fs.createWriteStream(filePath);
  
          response.data.pipe(writer);
  
          writer.on('finish', () => {
            writer.close();
            resolve({ savePath, fileName });
          });
  
          writer.on('error', error => {
            reject(error);
          });
  
          let downloadedBytes = 0;
          const totalBytes = parseInt(response.headers['content-length'], 10);
  
          response.data.on('data', data => {
            downloadedBytes += data.length;
            const progress = Math.round((downloadedBytes / totalBytes) * 100);
            progressCallback(progress);
          });
        })
        .catch(error => {
          reject(error);
        });
    });
  }


/**
 * 获取软件运行根目录
 * @returns 
 */
export function getMainPath() {
    if (process.env['ELECTRON_RENDERER_URL']) {
        // 开发模式
        return path.join(__dirname, '../../');
    }
    return path.join(__dirname, '../../../../');
}